﻿using System;
using System.Xml.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using UnityEngine;

public class MsgHandlers
{
        private MsgHandlers()
        {
        }
        private static MsgHandlers instance= new MsgHandlers();

        public static MsgHandlers getInstance()
        {
                return instance;
        }
        
        public void handleMsg(string msgStr)
        {
                JObject o = JObject.Parse(msgStr);
                JToken? jToken = o["msgId"];
                if (jToken == null)
                {
                        Debug.Log("不正确的消息json格式："+msgStr);
                        return;
                }

                int msgId = jToken.Value<int>();

                try
                {
                        if (msgId == MsgIdDefine.Resp_Login)
                        {
                                Resp_Login msg = JsonConvert.DeserializeObject<Resp_Login>(msgStr);
                                resp_Login(msg);
                                return;
                        }
                }
                catch (Exception e)
                {
                        Debug.LogError(e);
                }
        }
        
        public void resp_Login(IMsg msg)
        {
                Resp_Login respLogin = msg as Resp_Login;
                //TODO 创建实例
                Debug.Log("登录成功，角色名："+respLogin.name);
                GameObject gameObject = Resources.Load<GameObject>("prefabs/player/Player");
                GameObject obj =GameObject.Instantiate(gameObject,Vector3.zero,Quaternion.identity);
                if (obj != null)
                {
                        obj.name = "Player:" + respLogin.name;
                        Player player = new Player();
                        player.name = respLogin.name;
                        player.obj = obj;
                        PlayerManager.getInstance().mainPlayer = player;
                }
                else
                {
                        Debug.LogError("角色创建实例失败！");
                }
        }
}